package com.deng.api.jwt;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * JWT 认证过滤器
 */
@Component
@Slf4j
public class JWTAuthorizationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private JWTConfig jwtConfig;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Resource
    private UserDetailsService userDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        /**
         * token:  Bearer xxx.xxx.xx
         */
        //从请求头中获取token
        String header = request.getHeader(jwtConfig.header);

        //token不为空，却是定义的类型
        if (null !=header && header.startsWith(jwtConfig.tokenHead)){
            //解析出token
            String token = header.substring(jwtConfig.tokenHead.length());
            log.info("-----------前端传入的token:"+token);
            String userName = jwtTokenUtil.getUserNameFromToken(token);
            //如果token中有username，但是未登录
            if (userName != null && SecurityContextHolder.getContext().getAuthentication() == null){
                //登录处理
                UserDetails userDetails = userDetailsService.loadUserByUsername(userName);
                //验证token是否有效
                if (jwtTokenUtil.validateToken(token,userDetails)){
                    //证明token依然可以使用，那么可以生产一个认证凭证
                    UsernamePasswordAuthenticationToken authenticationToken
                            = new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
                    authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                }
            }
        }

        //过滤器继续往下执行
        filterChain.doFilter(request,response);
    }
}
